﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.ServiceProcess;
using System.Data.Sql;
using System.Data;
namespace OreSystem.Common
{
    public static class ToolSql
    {
        /// <summary>
        /// 判断是否安装了sql服务
        /// </summary>
        /// <returns></returns>
        public static bool ExistSqlServerService()
        {
            bool ExistFlag = false;
            ServiceController[] service = ServiceController.GetServices();
            foreach (var item in service)
            {
                string str = item.DisplayName;
            }
            var result = service.Where(a => a.ServiceName.ToUpper()=="MSSQLSERVER".ToUpper() || a.ServiceName.ToUpper()=="MSSQL$SQLEXPRESS".ToUpper());
            if (result != null)
            {
                ExistFlag = true;
            }
            //List<string> listName = new List<string>();
            //for (int i = 0; i < service.Length; i++)
            //{
                
            //    if (service[i].DisplayName.ToString().ToUpper().Contains("MSSQLSERVER"))
            //    {
            //        listName.Add(service[i].DisplayName.ToString());
            //        ExistFlag = true;
            //    }
            //}
            return ExistFlag;
        }

        //获取局域网中的sql服务器
        public static DataTable GetSqlServer()
        {
            SqlDataSourceEnumerator instance = SqlDataSourceEnumerator.Instance;
            DataTable table = instance.GetDataSources();
            return table;
        }

        #region 还原数据库
        public static void RestorDataBase(string dataBaseName, string backFile)
        {
            string restoreDataBase = @"USE MASTER
ALTER DATABASE {0} SET OFFLINE WITH ROLLBACK IMMEDIATE
RESTORE DATABASE OreSystemData
FROM DISK='{1}'
WITH REPLACE";
            string sql = string.Format(restoreDataBase, dataBaseName,backFile);
            MsSqlHelper.ExceuteNoQuery(sql, null);
        }
        #endregion
        #region 备份数据库
        public static void BackDataBase(string DataBaseName, string bakFile)
        {
            string sqlBackDatabase = string.Format(@"BACKUP DATABASE {0}
  TO DISK = '{1}' 
  WITH init;",DataBaseName,bakFile);
            MsSqlHelper.ExceuteNoQuery(sqlBackDatabase,null);
        }
        #endregion
    }
}
